<template>
	<view>
		<view class="main-block">
			<p>账户余额：￥{{balance}}</p>
			<view>
			<p v-if="$store.getters.staffInfo.companyId != 0">充值账户：{{ $store.getters.companyInfo.name }}<span style="text-indent: 5em;display: block;">@{{$store.getters.companyInfo.creditCode}}</span></p>
			<p v-else>充值账户：{{ $store.getters.staffInfo.name }}@{{$store.getters.staffInfo.idNumberHide }}</p>
			</view>
            <p v-if="$store.getters.staffInfo.companyId != 0">汇款人员：{{ $store.getters.staffInfo.name }}@{{$store.getters.staffInfo.idNumberHide}}</p>
		</view>
		<uni-section title="充值方式" type="line">
			<uni-data-select v-model="rechargeType" :localdata="rechargeArr" placeholder="请选择充值方式" :clear="false" />
		</uni-section>
		
		<!-- 在线充值 -->
		<view v-if="rechargeType == 0">
		<uni-section title="充值金额" type="line">
			<uni-easyinput v-model="amount" placeholder="请输入充值金额" />
		</uni-section>
		
		<!-- 支付方式 -->
		<uni-section title="支付方式" type="line">
			<uni-data-checkbox v-model="payType" :localdata="payArr"></uni-data-checkbox>
		</uni-section>
		
		<!-- 个人在线充值须知 -->
		<view class="introduce" v-if="$store.getters.staffInfo.companyId == 0">
			<view class="title">在线充值须知</view>
			<p>1、充值完成后，请前往【费用中心】， 点击【账户余额明细】查询详情；<br>
			2、充值资金不支持直接开票，需购买具体产品后，前往【我的订单】，根据产品消费订单申请发票。<br>
			3、充值款项仅用于励氪签平台产品消费，请您根据需求合理充值，如需退款，系统将根据退款时间扣除支付机构收取的服务费（使用微信充值超过1年后退款，系统将扣除微信收取的0.6%服务费；使用支付宝充值后退款，系统将扣除支付宝收取的0.6%服务费）。</p>
		</view>
		
		<!-- 企业在线充值须知 -->
		<view class="introduce" v-else>
			<view class="title">在线充值须知</view>
			<p>1、充值完成后，请前往【费用中心】， 点击【账户余额明细】查询详情；<br>
			2、充值资金不支持直接开票，需购买具体产品后，前往【企业订单】，根据产品消费订单申请发票。<br>
			3、充值款项仅用于励氪签平台产品消费，请您根据需求合理充值，如需退款，系统将根据退款时间扣除支付机构收取的服务费（使用微信充值超过1年后退款，系统将扣除微信收取的0.6%服务费；使用支付宝充值后退款，系统将扣除支付宝收取的0.6%服务费）。</p>
		</view>
		
		</view>
		
		<!-- 对公汇款 -->
		<view v-if="rechargeType == 1">
			<uni-section title="账户信息" type="line">
			<view class="company-header">
			  <p>励氪签对公账户信息</p>
			    <button size="mini" class="copy-btn" v-clipboard:copy="'企业对公账户信息：'
			                                 + '\n 账户名称：北京如易企服科技有限公司'
			                                 + '\n 银行账号：633917496'
			                                 + '\n 开户银行：中国民生银行股份有限公司北京回龙观支行'
			                                 + '\n 打款备注：账户充值'"
			             v-clipboard:success="clipboardSuccess" v-clipboard:error="clipboardError">复制信息</button>
			  </view>
			  <!-- 账号信息 -->
			  <view class="authentication_payCon">
			    <p>账户名称：北京如易企服科技有限公司</p>
			    <p>银行账号：633917496</p>
			    <p>开户银行：中国民生银行股份有限公司北京回龙观支行</p>
			    <p>打款备注：账户充值</p>
			</view>
			<!-- 上传付款回单 -->
			<uni-section type="line" title="付款凭证（仅支持 .jpg .jpeg .png 格式，文件小于3M。）">
				<uni-file-picker :limit="1" file-mediatype="all" file-extname="png,jpg,jpeg" :auto-upload="false" @select="selectUpload">
					<view class="up-file">
					<button>上传付款凭证</button>
					<view class="desc">打款后，请上传电子回单或汇款凭证图片，工作日预计1小时左右通过财务审核！</view>
					</view>
				</uni-file-picker>	
			</uni-section>
			</uni-section>

      <uni-section title="汇款金额" subTitle="请输入正确的汇款金额" type="line" padding>
        <uni-easyinput trim="all" v-model="amountRemit" type="number" placeholder="请输入汇款金额"></uni-easyinput>
      </uni-section>
			
			<!-- 个人对公汇款须知 -->
			<view class="introduce" v-if="$store.getters.staffInfo.companyId == 0">
				<view class="title">对公汇款须知</view>
				<p>1、充值完成后，请前往【费用中心】， 点击【账户余额明细】查询详情；<br>
				2、充值资金不支持直接开票，需购买具体产品后，前往【我的订单】，根据产品消费订单申请发票。<br>
				3、线下对公汇款预计1小时~ 3个工作日到账，汇款后请您提交汇款电子回单或汇款凭证；<br>
				4、充值款项仅用于励氪签平台产品消费，请您根据需求合理充值。</p>
			</view>
			
			<!-- 企业对公汇款须知 -->
			<view class="introduce" v-else>
				<view class="title">对公汇款须知</view>
				<p>1、充值完成后，请前往【费用中心】， 点击【账户余额明细】查询详情；<br>
				2、充值资金不支持直接开票，需购买具体产品后，前往【企业订单】，根据产品消费订单申请发票。<br>
				3、线下对公汇款预计1小时~ 3个工作日到账，汇款后请您提交汇款电子回单或汇款凭证；<br>
				4、充值款项仅用于励氪签平台产品消费，请您根据需求合理充值。</p>
			</view>
		</view>
		
		<view class="bottom-block">
			<checkbox-group v-if="rechargeType == 0" @change="select">
			  <label style="font-size: 26rpx;" v-for="item in checkboxPersonal" :key="item.name">
			  <checkbox :value="item.name" :checked="item.checked" color="#00a660" style="transform:scale(0.6);"/>
			  <span style="color:#00a660">{{item.value}}</span>
			  </label>
			</checkbox-group>
			<checkbox-group v-else @change="select">
			  <label style="font-size: 26rpx;" v-for="item in checkboxCompany" :key="item.name">
			  <checkbox :value="item.name" :checked="item.checked" color="#00a660" style="transform:scale(0.6);"/>
			  <span style="color:#00a660">{{item.value}}</span>
			  </label>
			</checkbox-group>
			<view class="btn-arr flex_between">
				<button @click="cancel">取 消</button>
				<button v-if="rechargeType == 0" @click="submitPer">确认充值</button>
				<button v-if="rechargeType == 1" @click="submitCom">提交汇款审核</button>
			</view>
		</view>
		
	</view>
</template>

<script>
import {getOrderStatus, payment} from "../../../../api/ec/person/fee/ecAccountBalancePay";
import {isWebView, isWechat} from "../../../../utils/validate";
import {getStaffInfo} from "../../../../api/ec/work/staff/staff";
import {getCompanyInfo} from "../../../../api/ec/work/company/company";
import {getToken} from "../../../../utils/auth";
import config from '@/config'

  export default {
		data() {
			return {
				checkVisable:true, //勾选框默认勾选true 
				checkboxPersonal: [{
				   name: '我已理解并同意上述《在线充值须知》',
				   value: '我已理解并同意上述《在线充值须知》',
				   checked: 'true'                 
				}],
				checkboxCompany: [{
				   name: '我已理解并同意上述《对公汇款须知》',
				   value: '我已理解并同意上述《对公汇款须知》',
				   checked: 'true'                 
				}],
				rechargeArr:[{
					text: '在线充值（即时到账）',
					value: 0
				}, {
					text: '对公汇款（预计一小时 ~ 3个工作日到账）',
					value: 1
				}],
				rechargeType:0,//充值方式
				amount:'',//充值金额
				amountRemit:'',//汇款金额
				payArr:[{
					text: '微信支付',
					value: "wxH5"
				}, {
					text: '支付宝支付',
					value: "alipayH5",
					disabled:'true'
				}],
				payType:"wxH5",//支付方式
				balance:'',//账户余额
				fileList: [],//上传
        interval:null,//定时查单
        wxCode:null,// 微信授权回调code
        // 轮训次数
        timerNumber: 0,
			}
		},
		onLoad(option) {
      this.wxCode = option.code;
      this.getBalance();
		},
    methods: {
      // 获取用户余额
      getBalance() {
        // 判断当前登录企业或者个人
        if (this.$store.getters.staffInfo.companyId == 0) {
          getStaffInfo().then(response => {
            this.balance = response.data.balance;//个人余额
          });
        } else {
          getCompanyInfo().then(response => {
            this.balance = response.data.balance;//企业余额
          });
        }
      },
      // 确认充值
      submitPer() {
        this.$modal.loading("支付中")
        if (this.amount == '') {
          this.$modal.msgError("请输入充值金额");
          return;
        } else if (this.checkVisable == false) {
          this.$modal.msgError("请先勾选打款认证须知");
          return;
        } else {
          this.codeVisible = true
        }
        // 判断环境若是微信h5环境进行公众号支付 若是小程序进行小程序支付 若是 h5浏览器 则进行微信h5支付
        if (isWebView()) { // TODO 小程序支付
        } else if (isWechat()) {  // jsapi支付
          this.paymentWxJsAPI("wxJsApi", this.amount);
        } else {  // h5 支付
          this.paymentWxH5("wxH5", this.amount);
        }
      },
      // 微信jsapi支付
      paymentWxJsAPI(payType,amount){
        let onBridgeReady = () => {
          payment(payType, amount, this.wxCode).then(response => {
            this.$modal.closeLoading();
            let data = response.data;
            WeixinJSBridge.invoke('getBrandWCPayRequest', {
                  "appId": data.appId,     //公众号ID，由商户传入
                  "timeStamp": data.timeStamp,     //时间戳，自1970年以来的秒数
                  "nonceStr": data.nonceStr,      //随机串
                  "package": data.prepayId,
                  "signType": "RSA",     //微信签名方式：
                  "paySign": data.paySign //微信签名
                }, res=> {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    this.$modal.msgSuccess("支付完成");
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  }
                });
            this.checkOrderStatus(data.orderId);
          }).catch(error => {
            this.$modal.closeLoading();
            this.$modal.msgError("支付异常");
          });

        }
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          }
        } else {
          onBridgeReady();
        }
      },
      // 微信h5支付
      paymentWxH5(payType,amount){
        payment(payType, amount).then(response => {
          this.$modal.closeLoading();
          let data = response.data;
          this.checkOrderStatus(data.orderId);
          window.location.href = data.codeUrl;
        }).catch(error => {
          this.$modal.closeLoading();
          this.$modal.msgError(error.msg);
        });
      },
      // 提交汇款审核
      submitCom() {
        if (this.fileList == '') {
          this.$modal.msgError("请先上传付款回单");
          return;
        } else if (this.checkVisable == false) {
          this.$modal.msgError("请先勾选打款认证须知");
          return;
        }
        this.$modal.loading();
        uni.uploadFile({
          url: config.baseUrl + "/ec/balancePay/payCard",
          filePath: this.fileList[0],
          header: {'Authorization': 'Bearer ' + getToken(),},
          name: 'file',
          formData: {'amount': this.amountRemit},
          success: (res) => {
            let response = JSON.parse(res.data);
            uni.hideLoading();
            if (response.code == 200) {
              uni.showModal({
                title: '提交成功,请等待审核',
                content: '是否查看余额充值记录？',
                cancelText: '取消',
                confirmText: '确定',
                success: (res) => {
                  if (res.confirm) {
                    this.$tab.reLaunch('/pages/mine/personal/product/balancePay/index')
                  }
                }
              })
            } else {
              this.$modal.msgError(response.msg)
            }
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      },
      // 检查支付订单状态
      checkOrderStatus(number) {
        this.interval = setInterval(() => {
          this.timerNumber++;
          // 定时器超时次数
          if (this.timerNumber == 30) {
            clearInterval(this.interval);
          }
          getOrderStatus(number).then(response => {
            // 支付完成
            if (response.data == 1) {
              //刷新余额
              this.getBalance();
              clearInterval(this.interval);
              uni.showModal({
                title: '恭喜！充值成功',
                content: '是否查看余额充值记录？',
                cancelText: '取消',
                confirmText: '确定',
                success: (res)=> {
                  if (res.confirm) {
                    this.$tab.reLaunch('/pages/mine/personal/product/balancePay/index')
                  }
                }
              })
            }
          });
        }, 3000);
      },
      // 取消
      cancel() {
        uni.navigateBack(1)
      },
      // 上传文件
      selectUpload(e){
        this.fileList= e.tempFilePaths;
      },
      /** 勾选框 */
      select(e) {
        if (e.detail.value.length == 0) {
          this.checkVisable = false
        } else {
          this.checkVisable = true
        }
      },
      /** 复制失败 */
      clipboardError() {
        this.$modal.msgError("复制失败");
      },
      /** 复制链接成功 */
      clipboardSuccess() {
        this.$modal.msgSuccess("复制成功");
      },

    }
	}
</script>

<style lang="scss" scoped>
	.up-file{
		display: flex;
		align-items: center;
		button{
			background: #fff;
			color: $uni-color-primary;
			border: 2rpx solid $uni-color-primary;
			width: 240rpx;
			height: 84rpx;
			line-height: 84rpx;
			font-size:26rpx;
		}
		.desc{
			width:60%;
			line-height: 28rpx;
			color: #777;
			font-size: 22rpx;
			margin-left: 10rpx;
		}
		
	}
	.authentication_payCon{
		background: #f8f8f8;
		padding: 15rpx 20rpx;
	}
	.company-header{
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  background: $uni-color-primary;
	  color: #fff;
	  padding: 12rpx 30rpx;
	  .copy-btn{
	    background: #fff;
	    height: 44rpx;
	    line-height: 44rpx;
	    color: $uni-color-primary;
		margin-right: 0;
	  }
	}
	.bottom-block{
		text-align: center;
		.btn-arr{
			width:80%;
			margin: 0 auto;
			button{
				font-size: 28rpx;
				width:240rpx;
			}
			button:first-child{
				border: 2rpx solid $uni-color-primary;
				background: #fff;
				color: $uni-color-primary;
			}
			button:last-child{
				background: $uni-color-primary;
				border: 2rpx solid $uni-color-primary;
				color: #fff;
			}
		}
	}
	.introduce{
		margin: 60rpx 0;
		background: #f8f8f8;
		padding: 20rpx;
		p{
			color: #666;
			font-size: 26rpx;
			margin-top: 10rpx;
			line-height: 38rpx;
		}
	}
	page{
		background:$uni-bg-color;
		padding: 40rpx;
	}
	.main-block{
		background: #f8f8f8;
		padding: 20rpx;
		color: #555;
	}
	::v-deep .uni-section .uni-section-header__decoration{
		background: $uni-color-primary;
	}
	::v-deep .uni-section .uni-section-header{
		padding: 24rpx 0 10rpx;
	}
	::v-deep .uni-data-checklist .checklist-group .checklist-box:last-child{
		margin-left: 40rpx;
	}
	::v-deep .uni-data-checklist .checklist-group .checklist-box .radio__inner{
		height: 30rpx;
		width: 30rpx;
	}
	::v-deep .uni-data-checklist .checklist-group .checklist-box .checklist-content .checklist-text{
		font-size: 26rpx;
	}

</style>
